//
//  JSWebConfiguration.m
//  JSWebDemo
//
//  Created by ac-hu on 2018/7/6.
//  Copyright © 2018年 ac-hu. All rights reserved.
//

#import "JSWebConfiguration.h"
#import "JSWebMethodManager.h"


@interface JSWebConfiguration()

@property(nonatomic,copy)NSString *userIdentifier;


@end
@implementation JSWebConfiguration
-(instancetype)initWithUserIdentifier:(NSString *)userIdentifier{
    if (self = [super init]) {
        [self initConfiguration];
        _userIdentifier = userIdentifier;
    }
    return self;
}

-(void)initConfiguration{
    //允许视频播放
    if (@available(iOS 9.0, *)) {
        self.allowsAirPlayForMediaPlayback = YES;
    }
    
    // 允许在线播放
    self.allowsInlineMediaPlayback = YES;
    // 允许可以与网页交互，选择视图
    self.selectionGranularity = YES;
    // web内容处理池
    self.processPool = [[WKProcessPool alloc] init];
    //自定义配置,一般用于 js调用oc方法(OC拦截URL中的数据做自定义操作)
    WKUserContentController * UserContentController = [[WKUserContentController alloc]init];
    
    //添加cookie
    NSString *cookieValue = [NSString stringWithFormat:@"document.cookie = 'PHPSESSIONID = %@';",@"6qg6vfrqs7sjm4h7oii993r1e4"];
//    添加cookie
//    NSString *cookieValue = [NSString stringWithFormat:@"document.cookie = '11111';"];
    WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:cookieValue injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
    [UserContentController addUserScript:cookieScript];
    
    // 添加消息处理，注意：self指代的对象需要遵守WKScriptMessageHandler协议，结束时需要移除
    [self addJsMethodWithUserContentController:UserContentController];
    // 是否支持记忆读取
    self.suppressesIncrementalRendering = YES;
    // 允许用户更改网页的设置
    self.userContentController = UserContentController;
}

- (void)addJsMethodWithUserContentController:(WKUserContentController *)userContentController {
    if ([JSWebMethodManager share].methods.count > 0 && userContentController != nil) {
        self.handler = [[JSWebMethodHandler alloc] init];
        for (int i = 0; i < [JSWebMethodManager share].methods.count; i++) {
            if ([[JSWebMethodManager share].methods[i] isKindOfClass:[NSString class]]) {
                //addScriptMessageHandler:对象 此对象需要遵守WKScriptMessageHandler协议
                [userContentController addScriptMessageHandler:self.handler name:[JSWebMethodManager share].methods[i]];
            }
        }
    }
}

-(void)removeConfig{
    [self.userContentController removeAllUserScripts];
    if (iOS_Version >= 11.0) {
        WarnDeprecatedStart
        if (@available(iOS 11.0, *)) {
            [self.userContentController removeAllContentRuleLists];
        } else {
            // Fallback on earlier versions
        }
        WarnDeprecatedEnd
    }
    
    for (NSString *methodName in [JSWebMethodManager share].methods) {
        [self.userContentController removeScriptMessageHandlerForName:methodName];
    }
    self.handler = nil;
}
@end
